//
//  XXX.swift
//  TarBarJump
//
//  Created by 郑东喜 on 2017/1/7.
//  Copyright © 2017年 郑东喜. All rights reserved.
//

import UIKit
import WebKit


class XXX: UIViewController,WKNavigationDelegate,WKUIDelegate,UIScrollViewDelegate {

    
    var webView = WKWebView()
    
    var refreshControl = UIRefreshControl()
    
    var tableView = UITableView()
    
    var progressView = UIProgressView()

    let SW = UIScreen.main.bounds.width
    let SH = UIScreen.main.bounds.height
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        webView = WKWebView()
        
        let configuration = WKWebViewConfiguration()
        let userContentController = WKUserContentController()
        
        configuration.userContentController = userContentController
        
        // 设置偏好设置
        let preferences = WKPreferences()
        
        // 在iOS上默认为NO，表示不能自动通过窗口打开
        preferences.javaScriptCanOpenWindowsAutomatically = true
        preferences.minimumFontSize = 10.0
        configuration.preferences = preferences
        
        configuration.processPool = WKProcessPool()
        webView = WKWebView.init(frame: view.bounds, configuration: configuration)
        
        webView.uiDelegate = self
        webView.navigationDelegate = self
        webView.scrollView.delegate = self
        
        
        webView.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil) // add observer for key path

        //https://www.baidu.com
        let url = URL.init(string: "http://yungou.ie1e.com/app/preorder_detail.aspx?id=35&sku=1166181712")
        
        
        self.webView.load(NSURLRequest.init(url: url!) as URLRequest)
        
        
        //添加wkwebView
        view.addSubview(webView)

    }
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if (keyPath == "estimatedProgress") { // listen to changes and updated view
            progressView.isHidden = webView.estimatedProgress == 1
            progressView.setProgress(Float(webView.estimatedProgress), animated: true)

        }
        
    }
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        print(webView.estimatedProgress)
    
        print("\((#file as NSString).lastPathComponent):(\(#line))",webView.scrollView.contentOffset.y)
        
        if webView.scrollView.contentOffset.y <= -64.0 && self.webView.estimatedProgress == 1.0 {
            print("kjhkjhdashdas")
            
            DispatchQueue.main.async {
                let rect = CGRect(x: 0, y: -64, width: self.SW, height: self.SH - 64)
                
                self.webView.scrollView.scrollRectToVisible(rect, animated: true)
            }

        }
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
    }


    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        print(scrollView.contentOffset.y)
        
        if scrollView.contentOffset.y <= -64.0 {
            webView.reload()
            
            if self.webView.isLoading == true {
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.5, execute: {
                    self.webView.frame = self.view.bounds
                })
            } else {
                
            }
            
        } else {
            return
        }
    }

    override func viewWillDisappear(_ animated: Bool) {
        self.webView.uiDelegate = nil
        self.webView.navigationDelegate = nil
    }
    
    
    
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        
        let request = navigationAction.request
        print(request)
        decisionHandler(.allow)
    }
    
    
    
    
}

